<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>发布考试 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            'status-pending': '#FFB800',
            'status-active': '#36D399',
            'status-expired': '#94A3B8'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
      .btn-start {
        @apply bg-secondary text-white border border-secondary px-3 py-1.5 rounded-lg transition-all duration-300 hover:bg-secondary/90 active:bg-secondary/80;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div class="flex items-center">
              <a href="#" class="text-gray-500 hover:text-primary mr-2">
                <i class="fa fa-arrow-left"></i>
              </a>
              <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">发布考试</h2>
            </div>
            <p class="text-gray-500 mt-1">管理所有未开始的考试，支持开始考试和删除操作</p>
          </div>

          <button class="btn-primary flex items-center self-start md:self-auto" id="create_exam_btn">
            <i class="fa fa-plus mr-2"></i> 新建考试
          </button>
        </div>
      </div>

      <!-- 筛选与搜索区域 -->
      <div class="bg-white rounded-xl p-5 card-shadow mb-6">
        <div class="flex flex-col md:flex-row flex-wrap gap-4">
          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700" for="filter-status">考试状态：</label>
            <select id="filter-status" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="all" selected>全部状态</option>
              <option value="0">未开始</option>
              <option value="1">进行中</option>
              <option value="2">已结束</option>
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700" for="filter-exam-type">考试类型：</label>
            <select id="filter-exam-type" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">全部类型</option>
              {% for exam_type in exam_type_options %}
                <option value="{{ exam_type }}">{{ exam_type }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="w-full md:w-auto flex items-center gap-3">
            <label class="text-sm font-medium text-gray-700" for="filter-class">所属班级：</label>
            <select id="filter-class" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
              <option value="">全部班级</option>
              {% for class_name in class_options %}
                <option value="{{ class_name }}">{{ class_name }}</option>
              {% endfor %}
            </select>
          </div>

          <div class="w-full md:flex-1 relative">
            <input id="filter-keyword" type="text" placeholder="搜索考试名称、科目、教师、试卷..."
                  class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
            <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
          </div>
        </div>
      </div>

      <!-- 考试列表 -->
      <div class="space-y-4 mb-6" id="exam-list"></div>
      <div id="pagination-container" class="mt-4"></div>
      <script type="application/json" id="initial-exams-data">{{ exams | tojson | safe }}</script>
      <script type="application/json" id="initial-pagination-data">{{ pagination_info | tojson | safe }}</script>
      <script>
        const create_exam_btn = document.getElementById('create_exam_btn');
        if (create_exam_btn) {
          create_exam_btn.addEventListener('click', () => {
            window.location.href = '/create_exams';
          });
        }

        const filterStatus = document.getElementById('filter-status');
        const filterExamType = document.getElementById('filter-exam-type');
        const filterClass = document.getElementById('filter-class');
        const filterKeyword = document.getElementById('filter-keyword');
        const examList = document.getElementById('exam-list');
        const paginationContainer = document.getElementById('pagination-container');

        const initialExamsRaw = document.getElementById('initial-exams-data');
        let initialExams = [];
        if (initialExamsRaw) {
          try {
            initialExams = JSON.parse(initialExamsRaw.textContent || '[]');
          } catch (error) {
            console.error('解析初始考试数据失败:', error);
            initialExams = [];
          }
        }

        const initialPaginationRaw = document.getElementById('initial-pagination-data');
        let initialPagination = null;
        if (initialPaginationRaw) {
          try {
            initialPagination = JSON.parse(initialPaginationRaw.textContent || 'null');
          } catch (error) {
            console.error('解析初始分页数据失败:', error);
            initialPagination = null;
          }
        }

        const initialPage = initialPagination && typeof initialPagination.page === 'number' ? initialPagination.page : 1;
        const initialPerPage = initialPagination && typeof initialPagination.per_page === 'number' ? initialPagination.per_page : 10;

        const escapeHtml = (value) => {
          if (value === null || value === undefined) {
            return '';
          }
          return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
        };

        const renderExams = (exams) => {
          if (!exams || !exams.length) {
            examList.innerHTML = `
              <div class="bg-white rounded-xl card-shadow p-6 text-center text-gray-500">
                暂无符合条件的考试记录。
              </div>
            `;
            return;
          }

          const cards = exams.map((exam) => {
            const classNames = Array.isArray(exam.class_names) && exam.class_names.length
              ? exam.class_names.map(escapeHtml).join('、')
              : '未设置';
            const durationText = exam.duration != null ? `${escapeHtml(exam.duration)} 分钟` : '未设置';
            const statusClass = escapeHtml(exam.status_class || 'bg-status-pending/20 text-status-pending');

            return `
              <div class="bg-white rounded-xl card-shadow overflow-hidden hover:shadow-lg transition-shadow">
                <div class="p-5 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div class="flex items-start gap-4">
                    <div class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary flex-shrink-0">
                      <i class="fa fa-file-text-o text-xl"></i>
                    </div>

                    <div class="flex-1">
                      <div class="flex flex-wrap items-center gap-2 mb-1">
                        <h3 class="font-bold text-lg">${escapeHtml(exam.name)}</h3>
                        <span class="px-2 py-0.5 text-xs rounded-full ${statusClass}">${escapeHtml(exam.status_label)}</span>
                        <span class="px-2 py-0.5 text-xs rounded-full bg-blue-100 text-blue-600">${escapeHtml(exam.exam_type || '未分类')}</span>
                      </div>

                      <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2 text-sm">
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-book text-gray-400 mr-2"></i>
                          <span>学科：${escapeHtml(exam.subject || '未设置')}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-users text-gray-400 mr-2"></i>
                          <span>班级：${classNames}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-clock-o text-gray-400 mr-2"></i>
                          <span>时间：${escapeHtml(exam.time_range || '未设置')}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-user text-gray-400 mr-2"></i>
                          <span>教师：${escapeHtml(exam.teacher_name || '未知教师')}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-file-text text-gray-400 mr-2"></i>
                          <span>试卷：${escapeHtml(exam.testpaper_name || '未知试卷')}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-hourglass-half text-gray-400 mr-2"></i>
                          <span>时长：${durationText}</span>
                        </div>
                        <div class="flex items-center text-gray-600">
                          <i class="fa fa-users text-gray-400 mr-2"></i>
                          <span>人数：${escapeHtml(exam.headcount != null ? exam.headcount : '未设置')}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="flex gap-2 self-end md:self-auto">
                    <button class="btn-start flex items-center text-sm" data-exam-id="${escapeHtml(exam.id)}">
                      <i class="fa fa-play mr-1"></i>开始考试
                    </button>
                    <button class="btn-danger flex items-center text-sm" data-exam-id="${escapeHtml(exam.id)}">
                      <i class="fa fa-trash mr-1"></i>删除
                    </button>
                  </div>
                </div>
              </div>
            `;
          }).join('');

          examList.innerHTML = cards;
          attachExamActionHandlers();
        };

        const state = {
          status: 'all',
          examType: '',
          className: '',
          keyword: '',
          page: initialPage,
          perPage: initialPerPage
        };

        let keywordTimer = null;

        const renderPagination = (pagination) => {
          if (!paginationContainer) {
            return;
          }
          if (!pagination || pagination.pages <= 1) {
            paginationContainer.innerHTML = '';
            return;
          }
          const currentPage = pagination.page || 1;
          const totalPages = pagination.pages || 1;
          let start = Math.max(1, currentPage - 2);
          let end = Math.min(totalPages, currentPage + 2);
          if (end - start < 4) {
            if (start === 1) {
              end = Math.min(totalPages, start + 4);
            } else if (end === totalPages) {
              start = Math.max(1, end - 4);
            }
          }
          const pageButtons = [];
          pageButtons.push(`
            <button data-page="${currentPage - 1}" ${pagination.has_prev ? '' : 'disabled'}
              class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm ${pagination.has_prev ? 'hover:bg-gray-100 text-gray-700' : 'text-gray-400 cursor-not-allowed'}">
              上一页
            </button>
          `);
          if (start > 1) {
            pageButtons.push(`
              <button data-page="1"
                class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm ${currentPage === 1 ? 'bg-primary text-white border-primary' : 'hover:bg-gray-100 text-gray-700'}">
                1
              </button>
            `);
            if (start > 2) {
              pageButtons.push('<span class="px-2 text-gray-400">...</span>');
            }
          }
          for (let page = start; page <= end; page += 1) {
            pageButtons.push(`
              <button data-page="${page}"
                class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm ${page === currentPage ? 'bg-primary text-white border-primary' : 'hover:bg-gray-100 text-gray-700'}">
                ${page}
              </button>
            `);
          }
          if (end < totalPages) {
            if (end < totalPages - 1) {
              pageButtons.push('<span class="px-2 text-gray-400">...</span>');
            }
            pageButtons.push(`
              <button data-page="${totalPages}"
                class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm ${currentPage === totalPages ? 'bg-primary text-white border-primary' : 'hover:bg-gray-100 text-gray-700'}">
                ${totalPages}
              </button>
            `);
          }
          pageButtons.push(`
            <button data-page="${currentPage + 1}" ${pagination.has_next ? '' : 'disabled'}
              class="px-3 py-1.5 border border-gray-300 rounded-lg text-sm ${pagination.has_next ? 'hover:bg-gray-100 text-gray-700' : 'text-gray-400 cursor-not-allowed'}">
              下一页
            </button>
          `);
          paginationContainer.innerHTML = `
            <div class="flex items-center justify-center gap-2">
              ${pageButtons.join('')}
            </div>
          `;
        };

        function attachExamActionHandlers() {
          if (!examList) {
            return;
          }
          const deleteButtons = examList.querySelectorAll('.btn-danger[data-exam-id]');
          deleteButtons.forEach((btn) => {
            btn.addEventListener('click', handleDeleteExam);
          });
          const startButtons = examList.querySelectorAll('.btn-start[data-exam-id]');
          startButtons.forEach((btn) => {
            btn.addEventListener('click', handleStartExam);
          });
        }

        if (paginationContainer) {
          paginationContainer.addEventListener('click', (event) => {
            const target = event.target.closest('button[data-page]');
            if (!target || target.disabled) {
              return;
            }
            const nextPage = Number(target.dataset.page);
            if (!Number.isNaN(nextPage) && nextPage >= 1) {
              state.page = nextPage;
              fetchAndRender();
            }
          });
        }

        const fetchAndRender = async () => {
          const params = new URLSearchParams();

          if (state.status && state.status !== 'all') {
            params.append('status', state.status);
          }
          if (state.examType) {
            params.append('exam_type', state.examType);
          }
          if (state.className) {
            params.append('class_name', state.className);
          }
          if (state.keyword) {
            params.append('keyword', state.keyword);
          }
          params.append('page', state.page);
          params.append('per_page', state.perPage);

          const queryString = params.toString();

          examList.innerHTML = `
            <div class="bg-white rounded-xl card-shadow p-6 text-center text-gray-500">
              正在加载...
            </div>
          `;

          try {
            const response = await fetch(`/api/exam_schedules${queryString ? `?${queryString}` : ''}`);
            if (!response.ok) {
              throw new Error('加载考试数据失败');
            }
            const data = await response.json();
            if (data.pagination && typeof data.pagination.page === 'number') {
              state.page = data.pagination.page;
            }
            if (data.pagination) {
              const totalPages = data.pagination.pages || 0;
              if (totalPages > 0 && state.page > totalPages) {
                state.page = totalPages;
                await fetchAndRender();
                return;
              }
              if (totalPages === 0 && state.page !== 1) {
                state.page = 1;
                await fetchAndRender();
                return;
              }
            }
            renderExams(data.exams || []);
            renderPagination(data.pagination || null);
          } catch (error) {
            examList.innerHTML = `
              <div class="bg-white rounded-xl card-shadow p-6 text-center text-red-500">
                ${escapeHtml(error.message || '加载考试数据失败')}
              </div>
            `;
            if (paginationContainer) {
              paginationContainer.innerHTML = '';
            }
          }
        };

        async function handleDeleteExam(event) {
          const trigger = event.currentTarget;
          const examId = trigger?.dataset?.examId;
          if (!examId) {
            return;
          }
          if (!confirm('确定要删除这个考试吗？此操作不可恢复。')) {
            return;
          }

          trigger.disabled = true;
          trigger.classList.add('opacity-60', 'pointer-events-none');
          try {
            const response = await fetch(`/api/exam_schedules/${encodeURIComponent(examId)}`, {
              method: 'DELETE'
            });
            if (!response.ok) {
              const data = await response.json().catch(() => ({ }));
              throw new Error(data.error || '删除考试失败');
            }
            await fetchAndRender();
          } catch (error) {
            alert(error.message || '删除考试失败，请稍后重试');
          } finally {
            trigger.disabled = false;
            trigger.classList.remove('opacity-60', 'pointer-events-none');
          }
        }

        async function handleStartExam(event) {
          const trigger = event.currentTarget;
          const examId = trigger?.dataset?.examId;
          if (!examId) {
            return;
          }
          if (!confirm('确定要开始这个考试吗？')) {
            return;
          }

          trigger.disabled = true;
          trigger.classList.add('opacity-60', 'pointer-events-none');
          try {
            const response = await fetch(`/api/exam_schedules/${encodeURIComponent(examId)}/start`, {
              method: 'POST'
            });
            if (!response.ok) {
              const data = await response.json().catch(() => ({ }));
              throw new Error(data.error || '开始考试失败');
            }
            await fetchAndRender();
          } catch (error) {
            alert(error.message || '开始考试失败，请稍后重试');
          } finally {
            trigger.disabled = false;
            trigger.classList.remove('opacity-60', 'pointer-events-none');
          }
        }

        filterStatus.addEventListener('change', () => {
          state.status = filterStatus.value;
          state.page = 1;
          fetchAndRender();
        });

        filterExamType.addEventListener('change', () => {
          state.examType = filterExamType.value;
          state.page = 1;
          fetchAndRender();
        });

        filterClass.addEventListener('change', () => {
          state.className = filterClass.value;
          state.page = 1;
          fetchAndRender();
        });

        filterKeyword.addEventListener('input', () => {
          clearTimeout(keywordTimer);
          keywordTimer = setTimeout(() => {
            state.keyword = filterKeyword.value.trim();
            state.page = 1;
            fetchAndRender();
          }, 400);
        });

        filterKeyword.addEventListener('keydown', (event) => {
          if (event.key === 'Enter') {
            event.preventDefault();
            clearTimeout(keywordTimer);
            state.keyword = filterKeyword.value.trim();
            state.page = 1;
            fetchAndRender();
          }
        });

        attachExamActionHandlers();
        renderExams(initialExams);
        renderPagination(initialPagination);
      </script>